var mask = null;
var dmtc = null;
var login_user = null
var stu_id = null;
var type = null;
var dkList = [];
var count = 0;
var packageid = null;
var packagename = null;
var twotype = null;
var contract_id = null;

$(function() { // 初始化内容
	mui.plusReady();
	mask = mui.createMask(); //遮罩层
	mui.init();
	tap_init();
	login_user = JSON.parse(localStorage.getItem('loginUser'));
	datetime_init();
	stu_id = sessionStorage.getItem('stu_id')
	contract_id = sessionStorage.getItem('contract_id')

	if (contract_id != null && contract_id != "" && contract_id != undefined) {
		loadContract();
	} else {

		if (stu_id != null && stu_id != "" && stu_id != undefined) {
			window.setTimeout(function() {
				getsaler();
				initContract();

			}, 500);
		}
	}

})

function tap_init() {

	jQuery(document).ready(function() {
		jQuery("#type").change(function() {
			app.select_Couese = [];
			app.todos = [];
			type = jQuery("#type").val();
			if (type == "口才系列" || type == "沟通系列" || type == "学习能力提升系列" || type == "365卓越系列") {
				jQuery("#course_type").removeAttr("style");
				dmtc = jQuery("#couese_status").val();
				jQuery("#couese_status").val("");
				jQuery("#tc").val("");

			} else if (type == "企业内训" || type == "个人辅导" || type == "复训" || type == "其他课程") {

				getCourse();
				jQuery("#course_type").css("display", "none");
				jQuery("#course_type").val("");
			} else {
				jQuery("#course_type").css("display", "none");
				getCourse()
			}

		});

		jQuery("#tra_amount").keyup(function() {
			var tra_amount = jQuery("#tra_amount").val();
			jQuery("#docasemoney").val(tra_amount);
			jQuery("#amount_notpaid").val(tra_amount);
			jQuery("#amount_paid").val(0);
		});

		jQuery("#couese_status").change(function() {
			var couese_status = jQuery("#couese_status").val();
			app.select_Couese = [];
			dmtc = couese_status;
			if (couese_status == "单课") {
				jQuery("#dk").removeAttr('style');
				jQuery("#tcMsg").css("display", "none");

			} else {
				jQuery("#tcMsg").removeAttr('style');
				jQuery("#dk").css("display", "none");

			}
			getCourse()
		});

		jQuery("#tc").change(function() {
			var tcid = jQuery("#tc").val();
			var tc_pay = jQuery("#tc").find("option:selected").attr("data_pay");
			jQuery("#amount").val(tc_pay);
			getTcDk(tcid);
			jQuery("#dk").removeAttr('style');
		});

	});

}

//数字转汉字
function intToChinese(str) {
	str = str + '';
	var len = str.length - 1;
	var idxs = ['', '十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千', '万', '十', '百', '千', '亿'];
	var num = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
	return str.replace(/([1-9]|0+)/g, function($, $1, idx, full) {
		var pos = 0;
		if ($1[0] != '0') {
			pos = len - idx;
			if (idx == 0 && $1[0] == 1 && idxs[len - idx] == '十') {
				return idxs[len - idx];
			}
			return num[$1[0]] + idxs[len - idx];
		} else {
			var left = len - idx;
			var right = len - idx + $1.length;
			if (Math.floor(right / 4) - Math.floor(left / 4) > 0) {
				pos = left - left % 4;
			}
			if (pos) {
				return idxs[pos] + num[$1[0]];
			} else if (idx + $1.length >= len) {
				return '';
			} else {
				return num[$1[0]];
			}
		}
	});
}

//小写值更改大写赋值
function putCaseNum(obj) {
	jQuery('#upcasemoney').val(intToChinese($(obj).val()));
}

function initContract() {
	var data = {};
	data['id'] = stu_id;
	jQuery.ajax({
		type: "post",
		headers: {
			'Authorization': login_user.token
		},
		url: serverip + "fxgw/newxy",
		contentType: 'application/json;charset=UTF-8',
		data: JSON.stringify(data),
		dataType: "json",
		timeout: 10000,
		beforeSend: function() {

			mask.show(); //显示遮罩层	
		},
		success: function(res) {
			mask.close(); //显示遮罩层 	  
			console.log("初始化合同信息=====" + JSON.stringify(res));
			var id = res.newxlc_contract.id;
			var stuMsg = res.stuList;
			jQuery("#id").val(id);
			jQuery("#schoolid").val(res.newxlc_contract.schoolid);
			jQuery("#stuid").val(stu_id);
			jQuery("#schoolname").val(res.newxlc_contract.schoolname);
			jQuery("#firstparty").val(res.newxlc_contract.firstparty);
			jQuery("#upschoolid").val(stuMsg.upschoolid);
			jQuery("#upschoolname").val(stuMsg.upschoolname);
			jQuery("#stuname").val(stuMsg.stuname);
			jQuery("#stutel").val(stuMsg.stutel);
			jQuery("#comingdate").val(stuMsg.comingdate);
			jQuery("#sfzh").val(stuMsg.sfzh);
			jQuery("#gender").val(stuMsg.stusex);
			jQuery("#stuwxid").val(stuMsg.qqwx);
			jQuery("#traperid").val(login_user.id);
			jQuery("#secondparty").val(stuMsg.stuname)

		},
		error: function(e) {
			console.log("错误信息====" + JSON.stringify(e));
			mask.close(); //显示遮罩层
			var msg = e.responseJSON.message;
			var code = e.responseJSON.status;
			mui.alert('错误编码' + code + "\n" + "错误信息:" + msg);
			console.log("错误信息====" + JSON.stringify(e));
		}
	});
}

function loadContract() {
	var data = {};
	data['id'] = contract_id;
	jQuery.ajax({
		type: "post",
		headers: {
			'Authorization': login_user.token
		},
		url: serverip + "fxgw/loadxy",
		contentType: 'application/json;charset=UTF-8',
		data: JSON.stringify(data),
		dataType: "json",
		timeout: 10000,
		beforeSend: function() {

			mask.show(); //显示遮罩层	
		},
		success: function(res) {
			mask.close(); //显示遮罩层 	  
			console.log("合同信息=====" + JSON.stringify(res));
			var id = res.newxlc_contract.id;
			loadForm(res.newxlc_contract);
			jQuery("#comingdate").val(res.newxlc_stu.comingdate);

		},
		error: function(e) {
			console.log("错误信息====" + JSON.stringify(e));
			mask.close(); //显示遮罩层
			var msg = e.responseJSON.message;
			var code = e.responseJSON.status;
			mui.alert('错误编码' + code + "\n" + "错误信息:" + msg);
			console.log("错误信息====" + JSON.stringify(e));
		}
	});
}


function getsaler() {
	var data = {};
	data['positions'] = "分校顾问"
	data['schoolid'] = login_user.schoolid;

	jQuery.ajax({
		type: "post",
		headers: {
			'Authorization': login_user.token
		},
		url: serverip + "newxlc_personnel/getsaler",
		contentType: 'application/json;charset=UTF-8',
		data: JSON.stringify(data),
		dataType: "json",
		timeout: 10000,
		beforeSend: function() {
			mask.show(); //显示遮罩层	
		},
		success: function(res) {
			mask.close(); //显示遮罩层 	  
			console.log("顾问列表=====" + JSON.stringify(res));

			jQuery("#traperid").find("option").remove();
			var str = "<option value=\"\">请选择</option>";
			for (var j = 0; j < res.length; j++) {
				str += "<option value=\"" + res[j].id + "\">" + res[j].name +
					"</option>";
			}
			jQuery("#traperid").append(str);
		},
		error: function(e) {
			console.log("错误信息====" + JSON.stringify(e));
			mask.close(); //显示遮罩层
			var msg = e.responseJSON.message;
			var code = e.responseJSON.status;
			mui.alert('错误编码' + code + "\n" + "错误信息:" + msg);
			console.log("错误信息====" + JSON.stringify(e));
		}
	});
}

function selectCourse() {
	window.location.href = "select_course.html"
	window.sessionStorage.setItem("courseType", type)
}

function loadApp1(data) {
	var arry = new Array();
	for (var i = 0; i < data.length; i++) {
		var d = data[i];
		var o = new Object();
		o.id = d.id + "-" + d.course_name;
		o.course_name = d.course_name;
		o.ischeck = false;
		if (d.istype != "未激活") {
			arry.push(o);
		}

	}
	console.log(JSON.stringify(arry));
	app.todos = arry;

}

function loadApp3(data) {
	var arry = new Array();
	for (var i = 0; i < data.length; i++) {
		var d = data[i];
		var o = new Object();
		o.id = d.id;
		o.course_pay = d.course_pay;
		o.course_name = d.course_name;
		o.ischeck = false;
		arry.push(o);
	}
	console.log(JSON.stringify(arry));
	app.todos = arry;

}

var app = new Vue({
	el: '#dk',
	data: {
		show: true,
		todos: [],
		status: false,
		select_Couese: []
	},
	methods: {
		getItem: function(todo) {
			console.log(JSON.stringify(this.select_Couese));
			todo.ischeck = !todo.ischeck;
			for (let item in this.todos) {

				if (item.id == todo.id) {
					item.ischeck = todo.ischeck;
				}
			}
			console.log(JSON.stringify(this.todos))

			console.log("······" + JSON.stringify(this.select_Couese));
			if (this.status == true) {
				if (this.select_Couese.length != 0) {
					for (var j = 0; j < this.select_Couese.length; j++) {
						for (var k = 0; k < this.todos.length; k++) {
							if (!this.todos[k].ischeck) {
								if (this.select_Couese[j] != undefined) {
									if (this.todos[k].id == this.select_Couese[j].id) {
										console.log("start---------------" + count);
										count = count - Number(this.select_Couese[j].course_pay)
										jQuery("#amount").val(count);
										console.log("after---------------" + count);
										this.select_Couese.splice(j, 1)
										console.log("hhhh" + JSON.stringify(this.select_Couese))
									}
								}
							}
						}
					}

				}

				for (var i = 0; i < this.todos.length; i++) {
					console.log(this.todos[i].ischeck);
					if (this.todos[i].ischeck == true) {
						console.log(this.select_Couese.length);
						if (this.select_Couese.length <= 2) {

							if (this.select_Couese.length == 0) {
								this.select_Couese.push(this.todos[i])
								console.log("start---------------" + count);
								count = Number(this.todos[i].course_pay);
								console.log("after---------------" + count);
								jQuery("#amount").val(count);
							} else {
								for (var j = 0; j < this.select_Couese.length; j++) {

									if (this.select_Couese[j].id != this.todos[i].id) {
										console.log("start---------------" + count);
										this.select_Couese.push(this.todos[i])
										count = count + Number(this.todos[i].course_pay);
										jQuery("#amount").val(count);
										console.log("after---------------" + count);
									}
								}
							}

						} else {
							console.log("=====" + JSON.stringify(this.select_Couese))
							mui.alert("只能选择两门课程");
							count = 0;
							jQuery("#amount").val(count);
							this.select_Couese = [];
							for (var s = 0; s < this.todos.length; s++) {
								this.todos[s].ischeck = false
							}

						}
					}
				}


			} else {

				if (this.select_Couese.length != 0) {
					for (var j = 0; j < this.select_Couese.length; j++) {
						for (var k = 0; k < this.todos.length; k++) {
							if (!this.todos[k].ischeck) {
								if (this.select_Couese[j] != undefined) {
									if (this.todos[k].id == this.select_Couese[j].id) {

										this.select_Couese.splice(j, 1)

									}
								}
							}
						}
					}

				}

				for (var i = 0; i < this.todos.length; i++) {
					var item = this.todos[i];
					var selectCouese = this.select_Couese;
					if (item.ischeck) {
						if (this.select_Couese.length == 0) {
							this.select_Couese.push(item)
						} else {

							this.select_Couese.find(function(value) {
								console.log("=====" + JSON.stringify(value))

								if (value.course_name === item.course_name) {

								} else {
									selectCouese.push(item)
								}
							});
							this.select_Couese = selectCouese;

						}

					}
				}
			}
			this.select_Couese = this.unuque(this.select_Couese);
			console.log("++++++" + JSON.stringify(this.select_Couese))

		},
		unuque: function(arr) {
			return Array.from(new Set(arr))
		}

	}

});
//获取课程信息
function getCourse() {
	var data = {};
	if (dmtc != null) {
		data['dmtc'] = dmtc;
	}
	if (type != null) {
		data['type'] = type;
	}

	jQuery.ajax({
		type: "post",
		headers: {
			'Authorization': login_user.token
		},
		url: serverip + "newxlc_course/loadNewxlc_courses",
		contentType: 'application/json;charset=UTF-8',
		data: JSON.stringify(data),
		dataType: "json",
		timeout: 10000,
		beforeSend: function() {
			mask.show(); //显示遮罩层	
		},
		success: function(res) {
			mask.close(); //显示遮罩层 	  
			console.log("课程信息=====" + JSON.stringify(res));
			jQuery("#couese_msg").removeAttr('style');
			if (type == "口才系列" || type == "沟通系列" || type == "学习能力提升系列" || type == "365卓越系列") {
				if (dmtc == "套餐") {
					twotype = "套餐";
					jQuery("#tc").find("option").remove();
					var str = "<option value=\"\">请选择</option>";
					for (var j = 0; j < res.length; j++) {
						str += "<option value=\"" + res[j].id + "\"" + ' ' + 'data_pay=' + "\"" + res[j].course_pay + "\">" + res[j].course_name +
							"</option>";
					}
					console.log("=====" + str)
					jQuery("#tc").append(str);
					app.$data.status = false;
				} else {

					loadApp3(res);
					app.$data.status = true;
				}

			} else if (type == "软实力卓越成就卡" || type == "软实力一卡通PLUS" || type == "软实力一卡通") {
				packageid = res[0].id;
				packagename = res[0].course_name;
				app.$data.status = false;
				getTcDk(res[0].id);
				jQuery("#amount").val(res[0].course_pay);

			} else if (type == "复训" || type == "其他课程") {
				app.$data.status = true;
				loadApp3(res);
			} else {
				app.$data.status = false;
				jQuery("#amount").val(res[0].course_pay);
				loadApp3(res);
			}

		},
		error: function(e) {
			console.log("错误信息====" + JSON.stringify(e));
			mask.close(); //显示遮罩层
			var msg = e.responseJSON.message;
			var code = e.responseJSON.status;
			mui.alert('错误编码' + code + "\n" + "错误信息:" + msg);
			console.log("错误信息====" + JSON.stringify(e));
		}
	});

}
//获取套餐内的单课信息
function getTcDk(tcid) {
	var data = {};
	data['stuid'] = stu_id;
	data['dktype'] = "true";
	data['page'] = "1";
	data['rows'] = "50";
	data['id'] = tcid;
	jQuery.ajax({
		type: "post",
		headers: {
			'Authorization': login_user.token
		},
		url: serverip + "newxlc_course/loadNewxlc_coursePage",
		contentType: 'application/json;charset=UTF-8',
		data: JSON.stringify(data),
		dataType: "json",
		timeout: 10000,
		beforeSend: function() {
			mask.show(); //显示遮罩层	
		},
		success: function(res) {
			mask.close(); //显示遮罩层 	  
			console.log("课程信息=====" + JSON.stringify(res));

			loadApp1(res.datas);

		},
		error: function(e) {
			console.log("错误信息====" + JSON.stringify(e));
			mask.close(); //显示遮罩层
			var msg = e.responseJSON.message;
			var code = e.responseJSON.status;
			mui.alert('错误编码' + code + "\n" + "错误信息:" + msg);
			console.log("错误信息====" + JSON.stringify(e));
		}
	});

}

function jointStr(arr, type) {
	var str = "";
	for (var i = 0; i < arr.length; i++) {
		if (i != arr.length - 1) {
			if (type == "id") {
				str += arr[i].id + ",";
			} else if (type == "name") {
				str += arr[i].course_name + ",";
			} else {

			}
		} else {
			if (type == "id") {
				str += arr[i].id;
			} else if (type == "name") {
				str += arr[i].course_name;
			} else {

			}
		}

	}
	console.log(str);
	return str
}

function jointStrTwo(arr, type) {
	var str = "";
	for (var i = 0; i < arr.length; i++) {
		if (i != arr.length - 1) {
			if (type == "id") {

				str += arr[i].id.split("-")[0] + ",";
			} else {
				str += arr[i].id.split("-")[1] + ",";
			}
		} else {
			if (type == "id") {
				str += arr[i].id.split("-")[0];
			} else {
				str += arr[i].id.split("-")[1];
			}
		}

	}
	console.log(str);
	return str;
}

function saveContract() {

	var data = jQuery("#pxfw_form").serializeObject();
	data['contractnumber'] = "协议编码";
	data['saler'] = jQuery("#traperid").val();
	data['salername'] = jQuery("#traperid").find("option:selected").text();
	data['oldtype'] = type;

	if (type == "软实力卓越成就卡" || type == "软实力一卡通PLUS" || type == "软实力一卡通") {
		data['dmtc'] = "套餐"
		data['coursenames'] = jointStrTwo(app.select_Couese, "name");
		data['courseids'] = jointStrTwo(app.select_Couese, "id");
		data['packageid'] = packageid;
		data['packagename'] = packagename;

	} else if (type == "口才系列" || type == "沟通系列" || type == "学习能力提升系列" || type == "365卓越系列") {
		var couese_status = jQuery("#couese_status").val();
		if (couese_status = "单课") {
			data['courseids'] = jointStr(app.select_Couese, "id");
			data['coursenames'] = jointStr(app.select_Couese, "name");
			data['dmtc'] = jQuery("#couese_status").val();
			data['twotype'] = jQuery("#couese_status").val();
		} else {
			data['courseids'] = jointStr(app.select_Couese, "id");
			data['coursenames'] = jointStr(app.select_Couese, "name");
			data['dmtc'] = jQuery("#couese_status").val();
			data['twotype'] = jQuery("#couese_status").val();
			data['packagename'] = jQuery("#tc").find("option:selected").text();
			data['packageid'] = jQuery("#tc").val();
		}

	} else {
		data['courseids'] = jointStr(app.select_Couese, "id");
		data['coursenames'] = jointStr(app.select_Couese, "name");
	}
	// else if (type == "复训" || type == "其他课程") {
	// 	data['courseids'] = jointStr(app.select_Couese, "id");
	// 	data['coursenames'] = jointStr(app.select_Couese, "name");

	// } 

	console.log(JSON.stringify(data))
	var arry = ["type","tra_amount","zzhtno","starttime","endtime"]
	if (judgeNull(arry)) {
		jQuery.ajax({
			type: "post",
			headers: {
				'Authorization': login_user.token
			},
			url: serverip + "fxgw/savexy",
			contentType: 'application/json;charset=UTF-8',
			data: JSON.stringify(data),
			dataType: "json",
			timeout: 10000,
			beforeSend: function() {
				mask.show(); //显示遮罩层	
			},
			success: function(res) {
				mask.close(); //显示遮罩层 	  
				console.log("res======" + JSON.stringify(res));
				mui.alert("提交成功")
				setTimeout(function() {
				
					mui.back();
				}, 2000)

			},
			error: function(e) {
				console.log("错误信息====" + JSON.stringify(e));
				mask.close(); //显示遮罩层
				var msg = e.responseJSON.message;
				var code = e.responseJSON.status;
				mui.alert('错误编码' + code + "\n" + "错误信息:" + msg);
				console.log("错误信息====" + JSON.stringify(e));
			}
		});
	} else {
		mui.alert("必填信息为空,请填写完全")
	}


}
